const express = require("express");
const { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE } = require("../server-env");
const bodyParser = require("body-parser");
const Service = require("./service");

function wrapAsync(fn) {
  return async function(req, res, next) {
    try {
      await fn(req, res, next)
    } catch(err) {
      next(err)
    }
  };
}

module.exports = (tableName, insertKeys = [], updateKeys = []) => {
  const router = express.Router();

  const service = new Service(tableName, insertKeys, updateKeys);

  // 获取所有数据
  router.get("/:id", wrapAsync(async (req, res) => {
    const id = req.params.id;
    const result = await service.get(id);
    res.json(result);
  }));

  // 分页获取数据
  router.get("/", wrapAsync(async (req, res) => {
    let page = req.query?.page || 1;

    const pageSize = Math.min(
      req.query?.pageSize || DEFAULT_PAGE_SIZE,
      MAX_PAGE_SIZE
    );

    const list = await service.list(page, pageSize);
    res.json(list);
  }));

  // 创建新数据
  router.post("/", bodyParser.json(), wrapAsync(async (req, res) => {
    const result = await service.insert(req.body);
    res.json(result);
  }));

  // 更新数据
  router.put("/:id", bodyParser.json(), wrapAsync(async (req, res) => {
    const id = req.params.id;
    const result = await service.update(id, req.body);
    res.json(result);
  }));

  // 删除数据
  router.delete("/:id", wrapAsync(async (req, res) => {
    const id = req.params.id;
    const result = await service.del(id);
    res.json(result);
  }));

  return router;
};
